package com.framework.loippi.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ID生成工具类，生成32位随机字符串
 * @author Shunzhong.Huang
 *
 */
public class IDManager {
	
	public static SimpleDateFormat DATETIMEFORMAT = new SimpleDateFormat("yyMMddHHmmss");
	
	public static Calendar calendar = Calendar.getInstance();
	
	public static Random random = new Random();
	
	public static AtomicInteger transferIdCount = new AtomicInteger(productRandom());
	
	private IDManager(){}
	
	/**
	 * 返回流转记录的ID主键
	 * @return
	 */
	public static String getTransferId() {
		int millisecond = calendar.get(Calendar.MILLISECOND);
		if(transferIdCount.get() >= 8000) {
			transferIdCount.set(productRandom());
		}
		int count = millisecond + transferIdCount.incrementAndGet();
		return DATETIMEFORMAT.format(new Date()) + cover(count);		
	}
	
	/**
	 * 补位
	 * @param millisecond
	 * @return
	 */
	private static String cover(int count) {
		String temp = String.valueOf(count);
		int len = temp.length();
		switch (len) {
		case 1:
			return "000"+temp;
		case 2:
			return "00"+temp;
		case 3:
			return "0"+temp;
		case 4:
			return temp;
		default:
			return temp.substring(0, 5);
		}
	}
	
	/**
	 * 通过参数时间，返回流转记录的ID主键
	 * @return
	 */
	public static String getTransferIdToTime(Date time) {
		int millisecond = calendar.get(Calendar.MILLISECOND);
		if(transferIdCount.get() >= 8000) {
			transferIdCount.set(productRandom());
		}
		int count = millisecond + transferIdCount.incrementAndGet();
		return DATETIMEFORMAT.format(time) + cover(count);		
	}
	
	/**
	 * 随机产生起始数
	 * @return
	 */
	private static int productRandom() {
		return random.nextInt(100) + 1;
	}
	
	/**
	 * UUID生成方法
	 * @return
	 */
	public static String getUUID(){		
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	
	
	public static void main(String  arg[]){
		System.out.println(getTransferId());
	}
}
